package com.unlcn.ils.sales.web.controller;

import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.unlcn.ils.sales.backend.bo.*;
import com.unlcn.ils.sales.backend.enums.OrderAuditStatusEnum;
import com.unlcn.ils.sales.backend.service.OrderAddrService;
import com.unlcn.ils.sales.backend.service.OrderAuditService;
import com.unlcn.ils.sales.backend.service.OrderService;
import com.unlcn.ils.sales.web.query.OrderQuery;
import com.unlcn.ils.sales.web.vo.OrderAuditVO;
import com.unlcn.ils.sales.web.vo.OrderDetailVO;
import com.unlcn.ils.sales.web.vo.OrderSkuVO;
import com.unlcn.ils.sales.web.vo.OrderViewVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017-06-15.
 */
@Controller
@RequestMapping(value = "/order")
public class OrderController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderAuditService orderAuditService;

    @Autowired
    private OrderAddrService orderAddrService;
    /**
     * 跳转列表页面
     * @return
     */
    @RequestMapping("/to-order-list")
    public String toListHtml(HttpServletResponse response,Model model) {
        response.setHeader("X-Frame-Options","ALLOW-FROM http://ils.unlcn.com/");
        ResultDTO<Object> result = new ResultDTO<>(true, null, "起运地下拉框显示");
        try {
            result.setData(orderAddrService.listAreaByCondition(""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("result",result);
        return "network/order-list";
    }

    /**
     * 跳转拒绝页面
     * @returnmvn clean package -Dmaven.test.skip=true

     */
    @RequestMapping("/to-refuse")
    public String toRefuseHtml() {
        return "network/order-refuse";
    }


    /**
     * 销售订单列表
     *
     * @param orderQuery 查询条件
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO<Object> list(@RequestBody OrderQuery orderQuery) {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "销售订单列表加载成功");
        PageVo pageVo = orderQuery.getPageVo();
        OrderQueryBO bo = new OrderQueryBO();
        BeanUtils.copyProperties(orderQuery, bo);
        try {
            if(StringUtils.isNotEmpty(orderQuery.getPickDateBegin())){
                bo.setPickDateBegin(StrToDate(orderQuery.getPickDateBegin()));
            }  if(StringUtils.isNotEmpty( orderQuery.getPickDateEnd())){
                bo.setPickDateEnd(StrToDate(orderQuery.getPickDateEnd()));
            }
            Map<String, Object> map = orderService.listSaleOrderToPc(pageVo, bo);
            List<OrderViewVO> orderDTOS = Lists.newArrayList();
            if (!Objects.equals(map, null) && map.size() > 0) {
                List<OrderViewBO> orders = (ArrayList) map.get("orderList");
                if (CollectionUtils.isNotEmpty(orders)) {
                    orders.stream().forEach(val -> {
                        OrderViewVO order = new OrderViewVO();
                        BeanUtils.copyProperties(val, order);
                        order.setOrderAuditStatusText(OrderAuditStatusEnum.getByValue(order.getAuditStatus()).getText());
                        orderDTOS.add(order);
                    });
                }
            }
            map.put("orderList", orderDTOS);
            result.setData(map);
        } catch (Exception e) {
            LOGGER.error("OrderController.list error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 销售订单审核
     *
     * 同意
     * @param ids 审核ID
     * @return
     */
    @RequestMapping(value = "/audit", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO<Object> audit( String ids) {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "销售订单审核成功");
        try {
            result.setData(orderAuditService.updateAuditStatus(ids));
        } catch (Exception e) {
            LOGGER.error("OrderController.list error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 销售订单更新
     * 拒绝
     *
     * @param vo 更新对象
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO<Object> update(OrderAuditVO vo) {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "销售订单审核成功");
        try {
            OrderAuditBO bo = new OrderAuditBO();
            BeanUtils.copyProperties(vo, bo);
            result.setData(orderAuditService.update(bo));
        } catch (Exception e) {
            LOGGER.error("OrderController.update error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 查询运单详情
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/detail")
    public String getSaleOrderDetail(Integer orderId, Model model) {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询销售订单明细成功");
        try {
            OrderDetailVO detailDTO = new OrderDetailVO();
            OrderViewBO viewBO = orderService.getSaleOrderByOrderId(orderId);
            BeanUtils.copyProperties(viewBO, detailDTO);
            if (!Objects.equals(viewBO, null) || !Objects.equals(viewBO, "")) {
                List<OrderSkuBO> skuBOS = viewBO.getOrderSkus();
                List<OrderSkuVO> skuDTOS = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(skuBOS)) {
                    skuBOS.stream().forEach(val -> {
                        OrderSkuVO skuDTO = new OrderSkuVO();
                        BeanUtils.copyProperties(val, skuDTO);
                        skuDTOS.add(skuDTO);
                    });
                }
                detailDTO.setOrderSkus(skuDTOS);
            }
            result.setData(detailDTO);
        } catch (Exception e) {
            LOGGER.error("OrderRest getSaleOrderDetail error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        model.addAttribute("result",result);
        return "network/order-detail";
    }

    /**
     * 字符串转换成日期
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (Exception e) {
            LOGGER.error("OrderRest getSaleOrderDetail error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return date;
    }
}
